java 集合类源码分析--collections
我认为Collections类主要是完成了两个主要功能
1.提供了若干简单而又有用的算法,比如排序,二分查找,求最大最小值等等。
2.提供对集合进行包装的静态方法。比如把指定的集合包装成线程安全的集合、包装成不可修改的集合、包装成类型安全的集合等。
package java.util;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;
public class Collections{
// Suppresses default constructor, ensuring non-instantiability.
private Collections() {
}
// 算法
/*
*
* 算法需要用到的一些参数。所有的关于List的算法都有两种实现,一种是适合随机访问的
* List,另一种是适合连续访问的。
*/
private static final int BINARYSEARCH_THRESHOLD = 5000;
private static final int REVERSE_THRESHOLD = 18;
private static final int SHUFFLE_THRESHOLD = 5;
private static final int FILL_THRESHOLD = 25;
private static final int ROTATE_THRESHOLD = 100;
private static final int COPY_THRESHOLD = 10;
private static final int REPLACEALL_THRESHOLD = 11;
private static final int INDEXOFSUBLIST_THRESHOLD = 35;
/**
*
* List中的所有元素必须实现Compareable接口,即每个 元素必须是可比的。
*
* 算法的实现原理为:
* 把指定的List转化为一个对象数组,对数组进行排序,然后迭代List的每一个元素,
* 在同样的位置重新设置数组中排好序的元素
*/
public static <T extends Comparable<? super T>> void sort(List<T> list) {
Object[] a = list.toArray(); //转化为对象数组用的归并
Arrays.sort(a); //对数组排序,使用了归并排序.对此归并的详细分析可见我另一篇博客
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) { //迭代元素
i.next();
i.set((T)a[j]); //在同样的位置重设排好序的值
}
}
/**
* 传一个实现了Comparator接口的对象进来。
* c.compare(o1,o2);来比较两个元素
*/
public static <T> void sort(List<T> list, Comparator<? super T> c) {
Object[] a = list.toArray();
Arrays.sort(a, (Comparator)c);
ListIterator i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set(a[j]);
}
}
/**
*
* 使用二分查找在指定List中查找指定元素key。
* List中的元素必须是有序的。如果List中有多个key,不能确保哪个key值被找到。
* 如果List不是有序的,返回的值没有任何意义
*
* 对于随机访问列表来说,时间复杂度为O(log(n)),比如1024个数只需要查找log2(1024)=10次,
* log2(n)是最坏的情况,即最坏的情况下都只需要找10次
* 对于链表来说,查找中间元素的时间复杂度为O(n),元素比较的时间复杂度为O(log(n))
*
* @return 查找元素的索引。如果返回的是负数表明找不到此元素,但可以用返回值计算
* 应该将key插入到集合什么位置,任然能使集合有序(如果需要插入key值的话)。
* 公式:point = -i - 1
*
*/
public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) {
if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
return Collections.indexedBinarySearch(list, key);
else
return Collections.iteratorBinarySearch(list, key);
}
/**
* 使用索引化二分查找。
* size小于5000的链表也用此方法查找
*/
private static <T> int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key){
int low = 0; //元素所在范围的下界
int high = list.size()-1; //上界
while (low <= high) {
int mid = (low + high) >>> 1;
Comparable<? super T> midVal = list.get(mid); //中间值
int cmp = midVal.compareTo(key); //指定元素与中间值比较
if (cmp < 0)
low = mid + 1; //重新设置上界和下界
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found
}
/**
* 迭代式二分查找,线性查找,依次查找得中间值
*
*/
private static <T> int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key){
int low = 0;
int high = list.size()-1;
ListIterator<? extends Comparable<? super T>> i = list.listIterator();
while (low <= high) {
int mid = (low + high) >>> 1;
Comparable<? super T> midVal = get(i, mid);
int cmp = midVal.compareTo(key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found
}
private static <T> T get(ListIterator<? extends T> i, int index) {
T obj = null;
int pos = i.nextIndex(); //根据当前迭代器的位置确定是向前还是向后遍历找中间值
if (pos <= index) {
do {
obj = i.next();
} while (pos++ < index);
} else {
do {
obj = i.previous();
} while (--pos > index);
}
return obj;
}
/**
* 提供实现了Comparator接口的对象比较元素
*/
public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {
if (c==null)
return binarySearch((List) list, key);
if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
return Collections.indexedBinarySearch(list, key, c);
else
return Collections.iteratorBinarySearch(list, key, c);
}
private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
int low = 0;
int high = l.size()-1;
while (low <= high) {
int mid = (low + high) >>> 1;
T midVal = l.get(mid);
int cmp = c.compare(midVal, key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found
}
private static <T> int iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
int low = 0;
int high = l.size()-1;
ListIterator<? extends T> i = l.listIterator();
while (low <= high) {
int mid = (low + high) >>> 1;
T midVal = get(i, mid);
int cmp = c.compare(midVal, key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found
}
private interface SelfComparable extends Comparable<SelfComparable> {}
/**
*
* 逆序排列指定列表中的元素
*/
public static void reverse(List<?> list) {
int size = list.size();
//如果是size小于18的链表或是基于随机访问的列表
if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--) //第一个与最后一个,依次交换
swap(list, i, j); //交换i和j位置的值
} else { //基于迭代器的逆序排列算法
ListIterator fwd = list.listIterator();
ListIterator rev = list.listIterator(size);
for (int i=0, mid=list.size()>>1; i<mid; i++) { //这..,一个思想你懂得
Object tmp = fwd.next();
fwd.set(rev.previous());
rev.set(tmp);
}
}
}
/**
*
* 对指定列表中的元素进行混排
*/
public static void shuffle(List<?> list) {
if (r == null) {
r = new Random();
}
shuffle(list, r);
}
private static Random r;
/**
*
* 提供一个随机数生成器对指定List进行混排
*
* 基本算法思想为:
* 逆向遍历list,从最后一个元素到第二个元素,然后重复交换当前位置
* 与随机产生的位置的元素值。
*
* 如果list不是基于随机访问并且其size>5,会先把List中的复制到数组中,
* 然后对数组进行混排,再把数组中的元素重新填入List中。
* 这样做为了避免迭代器大跨度查找元素影响效率
*/
public static void shuffle(List<?> list, Random rnd) {
int size = list.size();
if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
for (int i=size; i>1; i--) //从i-1个位置开始与随机位置元素交换值
swap(list, i-1, rnd.nextInt(i));
} else {
Object arr[] = list.toArray(); //先转化为数组
//对数组进行混排
for (int i=size; i>1; i--)
swap(arr, i-1, rnd.nextInt(i));
// 然后把数组中的元素重新填入List
ListIterator it = list.listIterator();
for (int i=0; i<arr.length; i++) {
it.next();
it.set(arr[i]);
}
}
}
/**
* 交换List中两个位置的值
*/
public static void swap(List<?> list, int i, int j) {
final List l = list;
l.set(i, l.set(j, l.get(i))); //互换i和j位置的值
}
/**
* 交换数组俩位置的值。好熟悉啊
*/
private static void swap(Object[] arr, int i, int j) {
Object tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
/**
*
* 用obj替换List中的所有元素
* 依次遍历赋值即可
*/
public static <T> void fill(List<? super T> list, T obj) {
int size = list.size();
if (size < FILL_THRESHOLD || list instanceof RandomAccess) {
for (int i=0; i<size; i++)
list.set(i, obj);
} else {
ListIterator<? super T> itr = list.listIterator();
for (int i=0; i<size; i++) {
itr.next();
itr.set(obj);
}
}
}
/**
*
* 复制源列表的所有元素到目标列表,
* 如果src.size > dest.size 将抛出一个异常
* 如果src.size < dest.size dest中多出的元素将不受影响
* 同样是依次遍历赋值
*/
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
int srcSize = src.size();
if (srcSize > dest.size())
throw new IndexOutOfBoundsException("Source does not fit in dest");
if (srcSize < COPY_THRESHOLD ||
(src instanceof RandomAccess && dest instanceof RandomAccess)) {
for (int i=0; i<srcSize; i++)
dest.set(i, src.get(i));
} else { //一个链表一个线性表也可以用迭代器赋值
ListIterator<? super T> di=dest.listIterator();
ListIterator<? extends T> si=src.listIterator();
for (int i=0; i<srcSize; i++) {
di.next();
di.set(si.next());
}
}
}
/**
*
* 返回集合中的最小元素。前提是其中的元素都是可比的,即实现了Comparable接口
* 找出一个通用的算法其实不容易,尽管它的思想不难。
* 反正要依次遍历完所有元素,所以直接用了迭代器
*/
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (next.compareTo(candidate) < 0)
candidate = next;
}
return candidate;
}
/**
* 根据提供的比较器求最小元素
*/
public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {
if (comp==null)
//返回默认比较器,其实默认比较器什么也不做,只是看集合元素是否实现了Comparable接口,
//否则抛出ClassCastException
return (T)min((Collection<SelfComparable>) (Collection) coll);
Iterator<? extends T> i = coll.iterator();
T candidate = i.next(); //假设第一个元素为最小元素
while (i.hasNext()) {
T next = i.next();
if (comp.compare(next, candidate) < 0)
candidate = next;
}
return candidate;
}
/**
* 求集合中最大元素
*/
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (next.compareTo(candidate) > 0)
candidate = next;
}
return candidate;
}
/**
* 根据指定比较器求集合中最大元素
*/
public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
if (comp==null)
return (T)max((Collection<SelfComparable>) (Collection) coll);
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (comp.compare(next, candidate) > 0)
candidate = next;
}
return candidate;
}
/**
*
* 旋转移位List中的元素通过指定的distance。每个元素移动后的位置为:
* (i + distance)%list.size.此方法不会改变列表的长度
*
* 比如,类表元素为: [t, a, n, k, s , w]
* 执行Collections.rotate(list, 2)或
* Collections.rotate(list, -4)后, list中的元素将变为
* [s, w, t, a, n , k]。可以这样理解:正数表示向后移,负数表示向前移
*
*/
public static void rotate(List<?> list, int distance) {
if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)
rotate1((List)list, distance);
else
rotate2((List)list, distance);
}
private static <T> void rotate1(List<T> list, int distance) {
int size = list.size();
if (size == 0)
return;
distance = distance % size; //distance始终处于0到size(不包括)之间
if (distance < 0)
distance += size; //还是以向后移来计算的
if (distance == 0)
return;
for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {
T displaced = list.get(cycleStart);
int i = cycleStart;
do {
i += distance; //求新位置
if (i >= size)
i -= size; //超出size就减去size
displaced = list.set(i, displaced); //为新位置赋原来的值
nMoved ++; //如果等于size证明全部替换完毕
} while(i != cycleStart); //依次类推,求新位置的新位置
}
}
private static void rotate2(List<?> list, int distance) {
int size = list.size();
if (size == 0)
return;
int mid = -distance % size;
if (mid < 0)
mid += size;
if (mid == 0)
return;
//好神奇啊
reverse(list.subList(0, mid));
reverse(list.subList(mid, size));
reverse(list);
}
/**
*
* 把指定集合中所有与oladVal相等的元素替换成newVal
* 只要list发生了改变就返回true
*/
public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {
boolean result = false;
int size = list.size();
if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {
if (oldVal==null) {
for (int i=0; i<size; i++) {
if (list.get(i)==null) {
list.set(i, newVal);
result = true;
}
}
} else {
for (int i=0; i<size; i++) {
if (oldVal.equals(list.get(i))) {
list.set(i, newVal);
result = true;
}
}
}
} else {
ListIterator<T> itr=list.listIterator();
if (oldVal==null) {
for (int i=0; i<size; i++) {
if (itr.next()==null) {
itr.set(newVal);
result = true;
}
}
} else {
for (int i=0; i<size; i++) {
if (oldVal.equals(itr.next())) {
itr.set(newVal);
result = true;
}
}
}
}
return result;
}
static class UnmodifiableSortedSet<E>
extends UnmodifiableSet<E>
implements SortedSet<E>, Serializable {
private static final long serialVersionUID = -4929149591599911165L;
private final SortedSet<E> ss;
UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
public Comparator<? super E> comparator() {return ss.comparator();}
public SortedSet<E> subSet(E fromElement, E toElement) {
return new UnmodifiableSortedSet<E>(ss.subSet(fromElement,toElement));
}
public SortedSet<E> headSet(E toElement) {
return new UnmodifiableSortedSet<E>(ss.headSet(toElement));
}
public SortedSet<E> tailSet(E fromElement) {
return new UnmodifiableSortedSet<E>(ss.tailSet(fromElement));
}
public E first() {return ss.first();}
public E last() {return ss.last();}
}
/**
* 返回一个 不可修改的List
* 如果原List实现了RandomAccess接口,返回的List也将实现此接口
*/
public static <T> List<T> unmodifiableList(List<? extends T> list) {
return (list instanceof RandomAccess ?
new UnmodifiableRandomAccessList<T>(list) :
new UnmodifiableList<T>(list));
}
/**
*
* 需要重新包装返回的EntrySet对象
*/
static class UnmodifiableEntrySet<K,V> extends UnmodifiableSet<Map.Entry<K,V>> {
private static final long serialVersionUID = 7854390611657943733L;
UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {
super((Set)s);
}
public Iterator<Map.Entry<K,V>> iterator() {
return new Iterator<Map.Entry<K,V>>() {
//父类UnmodifiableColletion的c
Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();
public boolean hasNext() {
return i.hasNext();
}
public Map.Entry<K,V> next() {
return new UnmodifiableEntry<K,V>(i.next());
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public Object[] toArray() {
Object[] a = c.toArray();
for (int i=0; i<a.length; i++)
a[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)a[i]);
return a;
}
public <T> T[] toArray(T[] a) {
Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
for (int i=0; i<arr.length; i++)
arr[i] = new UnmodifiableEntry<K,V>((Map.Entry<K,V>)arr[i]);
if (arr.length > a.length)
return (T[])arr;
System.arraycopy(arr, 0, a, 0, arr.length);
if (a.length > arr.length)
a[arr.length] = null;
return a;
}
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
return c.contains(new UnmodifiableEntry<K,V>((Map.Entry<K,V>) o));
}
public boolean containsAll(Collection<?> coll) {
Iterator<?> e = coll.iterator();
while (e.hasNext())
if (!contains(e.next())) // Invokes safe contains() above
return false;
return true;
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Set))
return false;
Set s = (Set) o;
if (s.size() != c.size())
return false;
return containsAll(s); // Invokes safe containsAll() above
}
/**
* 重新包装Entry。
*/
private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {
private Map.Entry<? extends K, ? extends V> e;
UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e) {this.e = e;}
public K getKey() {return e.getKey();}
public V getValue() {return e.getValue();}
public V setValue(V value) { //调用set方法将抛出一个异常
throw new UnsupportedOperationException();
}
public int hashCode() {return e.hashCode();}
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry t = (Map.Entry)o;
return eq(e.getKey(), t.getKey()) &&
eq(e.getValue(), t.getValue());
}
public String toString() {return e.toString();}
}
}
}
/**
* 返回一个线程安全的Set
*/
public static <T> Set<T> synchronizedSet(Set<T> s) {
return new SynchronizedSet<T>(s);
}
static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
return new SynchronizedSet<T>(s, mutex);
}
/**
* @serial include
*/
static class SynchronizedSet<E> extends SynchronizedCollection<E> implements Set<E> {
private static final long serialVersionUID = 487447009682186044L;
SynchronizedSet(Set<E> s) {
super(s);
}
SynchronizedSet(Set<E> s, Object mutex) {
super(s, mutex);
}
public boolean equals(Object o) {
synchronized(mutex) {return c.equals(o);}
}
public int hashCode() {
synchronized(mutex) {return c.hashCode();}
}
}
/**
* @serial include
*/
static class SynchronizedSortedSet<E> extends SynchronizedSet<E>implements SortedSet<E>{
private static final long serialVersionUID = 8695801310862127406L;
final private SortedSet<E> ss;
SynchronizedSortedSet(SortedSet<E> s) {
super(s);
ss = s;
}
SynchronizedSortedSet(SortedSet<E> s, Object mutex) {
super(s, mutex);
ss = s;
}
public Comparator<? super E> comparator() {
synchronized(mutex) {return ss.comparator();}
}
public SortedSet<E> subSet(E fromElement, E toElement) {
synchronized(mutex) {
return new SynchronizedSortedSet<E>(
ss.subSet(fromElement, toElement), mutex);
}
}
public SortedSet<E> headSet(E toElement) {
synchronized(mutex) {
return new SynchronizedSortedSet<E>(ss.headSet(toElement), mutex);
}
}
public SortedSet<E> tailSet(E fromElement) {
synchronized(mutex) {
return new SynchronizedSortedSet<E>(ss.tailSet(fromElement),mutex);
}
}
public E first() {
synchronized(mutex) {return ss.first();}
}
public E last() {
synchronized(mutex) {return ss.last();}
}
}
/**
* 返回一个线程安全的List,
* 如果List是基于随机访问的,返回的List同样实现了RandomAccess接口
*/
public static <T> List<T> synchronizedList(List<T> list) {
return (list instanceof RandomAccess ?
new SynchronizedRandomAccessList<T>(list) :
new SynchronizedList<T>(list));
}
static <T> List<T> synchronizedList(List<T> list, Object mutex) {
return (list instanceof RandomAccess ?
new SynchronizedRandomAccessList<T>(list, mutex) :
new SynchronizedList<T>(list, mutex));
}
/**
* @serial include
*/
static class SynchronizedList<E>extends SynchronizedCollection<E> implements List<E> {
static final long serialVersionUID = -7754090372962971524L;
final List<E> list;
SynchronizedList(List<E> list) {
super(list);
this.list = list;
}
SynchronizedList(List<E> list, Object mutex) {
super(list, mutex);
this.list = list;
}
public boolean equals(Object o) {
synchronized(mutex) {return list.equals(o);}
}
public int hashCode() {
synchronized(mutex) {return list.hashCode();}
}
public E get(int index) {
synchronized(mutex) {return list.get(index);}
}
public E set(int index, E element) {
synchronized(mutex) {return list.set(index, element);}
}
public void add(int index, E element) {
synchronized(mutex) {list.add(index, element);}
}
public E remove(int index) {
synchronized(mutex) {return list.remove(index);}
}
public int indexOf(Object o) {
synchronized(mutex) {return list.indexOf(o);}
}
public int lastIndexOf(Object o) {
synchronized(mutex) {return list.lastIndexOf(o);}
}
public boolean addAll(int index, Collection<? extends E> c) {
synchronized(mutex) {return list.addAll(index, c);}
}
public ListIterator<E> listIterator() {
return list.listIterator(); // Must be manually synched by user
}
public ListIterator<E> listIterator(int index) {
return list.listIterator(index); // Must be manually synched by user
}
public List<E> subList(int fromIndex, int toIndex) {
synchronized(mutex) {
return new SynchronizedList<E>(list.subList(fromIndex, toIndex),
mutex);
}
}
private Object readResolve() {
return (list instanceof RandomAccess
? new SynchronizedRandomAccessList<E>(list)
: this);
}
}
/**
* @serial include
*/
static class SynchronizedRandomAccessList<E>extends SynchronizedList<E>
implements RandomAccess {
SynchronizedRandomAccessList(List<E> list) {
super(list);
}
SynchronizedRandomAccessList(List<E> list, Object mutex) {
super(list, mutex);
}
public List<E> subList(int fromIndex, int toIndex) {
synchronized(mutex) {
return new SynchronizedRandomAccessList<E>(
list.subList(fromIndex, toIndex), mutex);
}
}
static final long serialVersionUID = 1530674583602358482L;
private Object writeReplace() {
return new SynchronizedList<E>(list);
}
}
/**
* 返回一个线程安全的map
*/
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
return new SynchronizedMap<K,V>(m);
}
/**
* @serial include
*/
private static class SynchronizedMap<K,V>
implements Map<K,V>, Serializable {
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 1978198479659022715L;
private final Map<K,V> m; // Backing Map
final Object mutex; // Object on which to synchronize
SynchronizedMap(Map<K,V> m) {
if (m==null)
throw new NullPointerException();
this.m = m;
mutex = this;
}
SynchronizedMap(Map<K,V> m, Object mutex) {
this.m = m;
this.mutex = mutex;
}
public int size() {
synchronized(mutex) {return m.size();}
}
public boolean isEmpty(){
synchronized(mutex) {return m.isEmpty();}
}
public boolean containsKey(Object key) {
synchronized(mutex) {return m.containsKey(key);}
}
public boolean containsValue(Object value){
synchronized(mutex) {return m.containsValue(value);}
}
public V get(Object key) {
synchronized(mutex) {return m.get(key);}
}
public V put(K key, V value) {
synchronized(mutex) {return m.put(key, value);}
}
public V remove(Object key) {
synchronized(mutex) {return m.remove(key);}
}
public void putAll(Map<? extends K, ? extends V> map) {
synchronized(mutex) {m.putAll(map);}
}
public void clear() {
synchronized(mutex) {m.clear();}
}
private transient Set<K> keySet = null;
private transient Set<Map.Entry<K,V>> entrySet = null;
private transient Collection<V> values = null;
public Set<K> keySet() {
synchronized(mutex) {
if (keySet==null)
keySet = new SynchronizedSet<K>(m.keySet(), mutex);
return keySet;
}
}
public Set<Map.Entry<K,V>> entrySet() {
synchronized(mutex) {
if (entrySet==null)
entrySet = new SynchronizedSet<Map.Entry<K,V>>(m.entrySet(), mutex);
return entrySet;
}
}
public Collection<V> values() {
synchronized(mutex) {
if (values==null)
values = new SynchronizedCollection<V>(m.values(), mutex);
return values;
}
}
public boolean equals(Object o) {
synchronized(mutex) {return m.equals(o);}
}
public int hashCode() {
synchronized(mutex) {return m.hashCode();}
}
public String toString() {
synchronized(mutex) {return m.toString();}
}
private void writeObject(ObjectOutputStream s) throws IOException {
synchronized(mutex) {s.defaultWriteObject();}
}
}
/**
*
* 返回一个动态的类型安全的集合。任何试图插入错误类型的元素的操作将立刻抛出
* ClassCastException
* 动态类型安全视图的一个主要作用是用作debug调试,
* 因为它能正确反映出出错的位置。
* 例如:ArrayList<String> strings = new ArrayList<String>();
* ArrayList rawList = strings;
* rawList.add(new Date());
* add方法并不进行类型检查,所以存入了非String的对象。只有在重新获取该对象
* 转化为String类型的时候才抛出异常。
* 而动态类型安全的集合能在add时就会抛出ClassCastException。
* 这种方法的优点是错误可以在正确的位置被报告
*
*
*/
public static <E> Collection<E> checkedCollection(Collection<E> c,Class<E> type) {
return new CheckedCollection<E>(c, type);
}
/**
* @serial include
*/
static class CheckedCollection<E> implements Collection<E>, Serializable {
private static final long serialVersionUID = 1578914078182001775L;
final Collection<E> c;
final Class<E> type;
void typeCheck(Object o) {
if (!type.isInstance(o)) //o是否能被转换成type类型
throw new ClassCastException("Attempt to insert " +
o.getClass() + " element into collection with element type "
+ type);
}
CheckedCollection(Collection<E> c, Class<E> type) {
if (c==null || type == null)
throw new NullPointerException();
this.c = c;
this.type = type;
}
public int size() { return c.size(); }
public boolean isEmpty() { return c.isEmpty(); }
public boolean contains(Object o) { return c.contains(o); }
public Object[] toArray() { return c.toArray(); }
public <T> T[] toArray(T[] a) { return c.toArray(a); }
public String toString() { return c.toString(); }
public boolean remove(Object o) { return c.remove(o); }
public boolean containsAll(Collection<?> coll) {
return c.containsAll(coll);
}
public boolean removeAll(Collection<?> coll) {
return c.removeAll(coll);
}
public boolean retainAll(Collection<?> coll) {
return c.retainAll(coll);
}
public void clear() {
c.clear();
}
public Iterator<E> iterator() {
return new Iterator<E>() {
private final Iterator<E> it = c.iterator();
public boolean hasNext() { return it.hasNext(); }
public E next() { return it.next(); }
public void remove() { it.remove(); }};
}
public boolean add(E e){
typeCheck(e); //添加元素需要进行类型检查
return c.add(e);
}
public boolean addAll(Collection<? extends E> coll) {
E[] a = null;
try {
a = coll.toArray(zeroLengthElementArray()); //根据zero数组的类型来转换集合为数组。如果coll中含有其他类型这里就会抛出异常
} catch (ArrayStoreException e) {
throw new ClassCastException();
}
boolean result = false;
for (E e : a)
result |= c.add(e); //只要集合发生了改变就返回true
return result;
}
private E[] zeroLengthElementArray = null; // Lazily initialized
/*
* We don't need locking or volatile, because it's OK if we create
* several zeroLengthElementArrays, and they're immutable.
*/
E[] zeroLengthElementArray() {
if (zeroLengthElementArray == null)
zeroLengthElementArray = (E[]) Array.newInstance(type, 0);
return zeroLengthElementArray;
}
}
/**
* 返回一个会检查类型的集合Set
*/
public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
return new CheckedSet<E>(s, type);
}
/**
* @serial include
*/
static class CheckedSet<E> extends CheckedCollection<E>
implements Set<E>, Serializable{
private static final long serialVersionUID = 4694047833775013803L;
CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }
public boolean equals(Object o) { return o == this || c.equals(o); }
public int hashCode() { return c.hashCode(); }
}